package com.system.honour.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.system.honour.common.ResultDTO;
import com.system.honour.entity.SysPermission;
import com.system.honour.entity.SysRole;
import com.system.honour.entity.SysRolePermission;
import com.system.honour.entity.SysRoleUser;
import com.system.honour.exception.CustomizeErrorCode;
import com.system.honour.mapper.SysPermissionMapper;
import com.system.honour.mapper.SysRoleMapper;
import com.system.honour.mapper.SysRolePermissionMapper;
import com.system.honour.mapper.SysRoleUserMapper;
import com.system.honour.service.PermissionService;
import com.system.honour.util.TreeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@Transactional
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private SysPermissionMapper permissionMapper;
    @Autowired
    private SysRolePermissionMapper rolePermissionMapper;
    @Autowired
    private SysRoleMapper roleMapper;
    @Autowired
    private SysRoleUserMapper roleUserMapper;

    @Override
    public ResultDTO findByAll() {
        List<SysPermission> permissionList = permissionMapper.findByAll();
        JSONArray array = new JSONArray();
        TreeUtils.setPermissionsTree(0,permissionList,array);
        return ResultDTO.okOf(array);
    }

    @Override
    public ResultDTO getListByRoleId(Integer roleId) {
        SysRole role = roleMapper.selectByPrimaryKey(roleId);
        if (role==null){
            return ResultDTO.errorOf(CustomizeErrorCode.INCORRECT_INFORMATION);
        }
        List<SysPermission> sysPermissions = new ArrayList<>();
        List<SysRolePermission> rolePermissions = rolePermissionMapper.getByRoleId(role.getId());
        if (rolePermissions!=null&&rolePermissions.size()>0){
            for (int i = 0; i < rolePermissions.size(); i++) {
                Integer pid = rolePermissions.get(i).getPermissionId();
                if (pid!=null){
                    SysPermission permission = permissionMapper.selectByPrimaryKey(pid);
                    if (permission!=null){
                        sysPermissions.add(permission);
                    }
                }
            }
            return ResultDTO.okOf(sysPermissions);
        }
        return ResultDTO.errorOf(CustomizeErrorCode.INCORRECT_INFORMATION);
    }

    @Override
    public ResultDTO findMenuAll() {
        List<SysPermission> permissionList = permissionMapper.findByAll();
        return ResultDTO.okOf(permissionList);
    }

    @Override
    public ResultDTO save(SysPermission permission) {
        //获取父级id
        Integer pid = permission.getParentId();
        Integer newPid =0;
        if (pid==null){
            pid=newPid;
        }
        if (pid != 0){
            //判断父级是否存在
            SysPermission permission1 = permissionMapper.selectByPrimaryKey(pid);
            if (permission1==null){
                return ResultDTO.errorOf(CustomizeErrorCode.INCORRECT_INFORMATION);
            }
        }
        //判断同一父级内名称不相同
        if (checkNameExist(permission.getName(),permission.getParentId())){
            return ResultDTO.errorOf(CustomizeErrorCode.INCORRECT_INFORMATION);
        }
        permissionMapper.insertSelective(permission);
        return ResultDTO.okOf(permission);
    }

    @Override
    public ResultDTO update(SysPermission permission) {
        if (permission.getId()==null){
            return ResultDTO.errorOf(CustomizeErrorCode.INCORRECT_INFORMATION);
        }
        //同一父级内名称不相同
        if (checkNameExist(permission.getName(),permission.getParentId())){
            return ResultDTO.errorOf(CustomizeErrorCode.INCORRECT_INFORMATION);
        }
        permissionMapper.updateByPrimaryKeySelective(permission);
        return ResultDTO.okOf();
    }

    @Override
    public ResultDTO deleteById(Integer id) {
        //1.删除权限 && 权限之下的子节点 && 子节点之下的子节点

        //2.删除角色权限关联表中相关的id
        return null;
    }

    @Override
    public ResultDTO getMenuByUserId(Integer userId) {
        List<SysPermission> permissions = getListByUserId(userId);
        List<SysPermission> permissionList = new ArrayList<>();
        if (permissions!=null&&permissions.size()>0){
            for (int i = 0; i < permissions.size(); i++) {
                SysPermission permission = permissions.get(i);
                if (permission.getType().equals(1)){
                    permissionList.add(permission);
                }
            }
        }
        JSONArray array = new JSONArray();
        TreeUtils.setPermissionsTree(0,permissionList,array);
        return ResultDTO.okOf(array);
    }

    @Override
    public List<SysPermission> getListByUserId(Integer userId) {
        //1.获取用户的角色信息
        List<SysRoleUser> byUserIds = roleUserMapper.getByUserId(userId);
        List<Integer> roles = new ArrayList<>();
        if (byUserIds!=null&&byUserIds.size()>0){
            for (int i = 0; i < byUserIds.size(); i++) {
                SysRoleUser roleUser = byUserIds.get(i);
                Integer roleId = roleUser.getRoleId();
                roles.add(roleId);
            }
        }
        //2.根据角色信息获取权限信息
        List<Integer> pids = new ArrayList<>();
        if (roles!=null&&roles.size()>0){
            for (int i = 0; i < roles.size(); i++) {
                List<SysRolePermission> byRolepIds = rolePermissionMapper.getByRoleId(roles.get(i));
                if (byRolepIds!=null&&byRolepIds.size()>0){
                    for (int j = 0; j < byRolepIds.size(); j++) {
                        SysRolePermission rolePermission = byRolepIds.get(j);
                        Integer rolePid = rolePermission.getPermissionId();
                        pids.add(rolePid);
                    }
                }
            }
        }
        //3.根据权限id和菜单类型获取相关菜单权限
        List<SysPermission> permissionList = new ArrayList<>();
        if (pids!=null&& pids.size()>0){
            for (int i = 0; i < pids.size(); i++) {
                SysPermission sysPermission = permissionMapper.selectByPrimaryKey(pids.get(i));
                permissionList.add(sysPermission);
            }
        }

        return permissionList;
    }




    /**
     * 同一父级内名称不相同
     * @param name
     * @param parentId
     * @return
     */
    private boolean checkNameExist(String name,Integer parentId){
        return permissionMapper.countByName(name,parentId)>0;
    }


}
